<template>
  <div class="sort">
    <div class="search-container">
      <!-- <div class="search-inp-container">
        <el-input @keyup.enter.native="handleSearch" placeholder="输入标题" v-model="listQuery.title" clearable>
        </el-input>
      </div>
      <el-button class="search-btn" type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>-->
      <el-button
        class="search-btn"
        type="primary"
        icon="el-icon-plus"
        v-if="mall_ad_add"
        @click="handleAdd"
      >{{$t('m.ADD')}}</el-button>
      <el-button
        class="search-btn"
        :autofocus="true"
        icon="el-icon-refresh"
        @click="refreshHandle"
      >{{$t('m.REFRESH')}}</el-button>
    </div>
    <el-table :key="tableKey" :data="list" v-loading="listLoading" border fit highlight-current-row>
      <el-table-column align="center" prop="typeNum" :label="$t('m.TYPE_NUM')"></el-table-column>
      <el-table-column align="center" prop="typeName" :label="$t('m.TYPE_NAME')"></el-table-column>
      <el-table-column align="center" :label="$t('m.CREATE_TIME')">
        <template slot-scope="scope">
          <span>{{scope.row.createTime}}</span>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        :label="$t('m.OPERATION')"
        width="300"
        v-if="mall_ad_del  || mall_ad_update "
      >
        <template align="center" slot-scope="scope">
          <el-button
            v-if="mall_ad_get"
            size="mini"
            type="primary"
            @click="handleGet(scope.row)"
          >{{$t('m.VIEW')}}</el-button>
          <el-button
            v-if="mall_ad_update"
            size="mini"
            type="primary"
            @click="handleEdit(scope.row)"
          >{{$t('m.EDIT')}}</el-button>
          <el-button
            v-if="mall_ad_del"
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >{{$t('m.DELECT')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.current"
        :page-size="listQuery.size"
        :page-sizes="[10, 40, 80, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="40%"
      :close-on-click-modal="false"
      @close="cancel('form')"
      custom-class="sort-dialog"
    >
      <el-scrollbar style="height:100%" class="sort-scrollbar" wrap-class="sort-scrollbar__wrap">
        <el-form
          :model="form"
          :rules="rules"
          ref="form"
          label-width="100px"
          enctype="multipart/form-data"
        >
          <el-form-item
            class="w347"
            :label="$t('m.TYPE_NAME')"
            placeholder="请输入物资类型"
            prop="typeName"
          >
            <el-input v-model="form.typeName" maxlength="12" :disabled="disabled"></el-input>
          </el-form-item>

          <el-form-item class="w347" :label="$t('m.TYPE_NUM')" placeholder="请输入物资类型" prop="typeNum">
            <el-input v-model="form.typeNum" maxlength="12" :disabled="disabled"></el-input>
          </el-form-item>
          <!-- 类型属性 -->
          <el-form-item :label="$t('m.TYPE_PROP')" prop="isShow">
            <el-form-item label prop="isShow">
              <el-button
                v-if="!disabled"
                type="primary"
                @click="addDomain($event)"
              >{{$t('m.ADD_PROP')}}</el-button>
            </el-form-item>
          </el-form-item>

          <el-form-item v-for="(domain,index) in form.propList" :key="domain.key">
            <el-form-item>
              <template>
                <el-col>
                  <label>{{$t('m.LABEL')}}</label>
                  <el-input
                    v-model="domain.propLabel"
                    placeholder
                    @input="change($event)"
                    style="width: 30%"
                    :disabled="disabled"
                  ></el-input>
                  <label>{{$t('m.NAME')}}</label>
                  <el-input
                    v-model="domain.propName"
                    placeholder
                    @input="change($event)"
                    style="width: 30%"
                    :disabled="disabled"
                  ></el-input>
                  <el-button
                    v-if="!disabled"
                    type="primary"
                    @click.prevent="removeDomain(domain)"
                  >{{$t('m.DELECT')}}</el-button>
                </el-col>
              </template>
            </el-form-item>
          </el-form-item>
          <!-- 阈值管理 -->
          <el-form-item :label="$t('m.THRESHOLD_VALUE')" prop="isShow">
            <el-form-item label prop="isShow">
              <el-button
                v-if="!disabled"
                type="primary"
                @click="addThreshold($event)"
              >{{$t('m.ADD_THRESHOLD_VALUE')}}</el-button>
            </el-form-item>
          </el-form-item>
          <el-form-item v-for="(domain,index) in form.thresholdList" :key="domain.key">
            <el-form-item>
              <template>
                <el-col>
                  <label>{{$t('m.LABEL')}}</label>
                  <el-input
                    v-model="domain.label"
                    placeholder
                    @input="change($event)"
                    style="width: 30%"
                    :disabled="disabled"
                  ></el-input>
                  <label>{{$t('m.VALUE')}}</label>
                  <el-input
                    v-model="domain.value"
                    placeholder
                    @input="change($event)"
                    style="width: 30%"
                    :disabled="disabled"
                  ></el-input>
                  <el-button
                    v-if="!disabled"
                    type="primary"
                    @click.prevent="removeThreshold(domain)"
                  >{{$t('m.DELECT')}}</el-button>
                </el-col>
              </template>
            </el-form-item>
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">{{$t('m.CANCEL')}}</el-button>
        <el-button
          v-if="dialogStatus=='create'&& !disabled"
          type="primary"
          @click="create('form')"
        >{{$t('m.CONFIRM')}}</el-button>
        <el-button
          v-if="dialogStatus=='update'&& !disabled"
          type="primary"
          @click="update('form')"
        >{{$t('m.UPDATE')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { setToken } from '@/utils/auth'
import { fetchList, delObj, getObj, addObj, putObj, getToken } from '@/api/sort'
import { getTopDictListByDescNew } from '@/api/dict'
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      imageUrl: '',
      tableKey: 0,
      listLoading: false,
      list: [],
      orgOptions: [],
      listQuery: {
        current: 1,
        size: 10,
        // desc: 'create_date'
      },
      total: 0,
      mall_ad_add: true,
      mall_ad_update: true,
      mall_ad_del: true,
      mall_ad_get: true,
      dialogFormVisible: false,
      url: '',
      imgUpload: process.env.BASE_API + '/mall/ad/imgUpload/',
      form: {
        typeName: '',
        typeId: '',
        typeNum: '',
        propList: [
          {
            propLabel: undefined,
            propName: undefined,
          },
        ],
        thresholdList: [
          {
            label: undefined,
            value: undefined,
          },
        ],
      },
      rules: {
        typeName: [
          { required: true, message: '请输入物资类型', trigger: 'blur' },
        ],
        typeNum: [
          { required: true, message: '请输入物资编号', trigger: 'blur' },
        ],
      },
      textMap: {
        update: '编辑',
        create: '创建',
        get: '查看',
      },
      dialogStatus: '',
      role: [],
      typeOptions: [],
      isShowOptions: [],
      isDisabled: {
        0: false,
        1: true,
      },
      statusOptions: ['0', '1'],
      dialogDeptVisible: false,
      treeDeptData: [],
      checkedKeys: [],
      typeList: [],
      disabled: false,
    }
  },

  components: {},
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: '否',
        1: '是',
        9: '锁定',
      }
      return statusMap[status]
    },
  },
  computed: {
    ...mapGetters(['permissions']),
  },

  mounted() {
    const query = location.search.substring(1)
    console.log('登录信息' + query)
    if (query) {
      const token = query.split('=')
      if (token[1] === 'idispatch') {
        console.log('调度台嵌入')
        sessionStorage.setItem('type', token[1])
      }
    }
    this.getList()
    // this.mall_ad_add = this.permissions['/mall/ad:add']
    // this.mall_ad_update = this.permissions['/mall/ad:update']
    // this.mall_ad_del = this.permissions['/mall/ad:del']
    // this.sys_user_select = this.permissions['/admin/user:select']
    // var websocket = null
    // if ('WebSocket' in window) {
    //   websocket = new WebSocket(
    //     // 'ws://localhost:8089/materials/websocket/testname'
    //     // 'ws://zhangr.utools.club/materials/websocket/testname'
    //     'ws://10.20.56.144:8089/materials/websocket/testname'
    //   )
    // }
    // websocket.onopen = function () {
    //   console.log('连接成功')
    // }
    // websocket.onclose = function () {
    //   console.log('退出连接')
    // }
    // websocket.onmessage = function (event) {
    //   console.log('收到消息' + event.data)
    // }
    // websocket.onerror = function () {
    //   console.log('连接出错')
    // }
    // window.onbeforeunload = function () {
    //   websocket.close(num)
    // }
  },

  methods: {
    getList() {
      this.listLoading = true
      this.listQuery.isAsc = false
      fetchList(this.listQuery).then((response) => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
        if (this.listQuery.current != 1 && this.list.length == 0) {
          this.listQuery.current = this.listQuery.current - 1
          this.getList()
        }
      })
    },
    refreshHandle() {
      this.listQuery.current = 1
      this.listQuery.size = 10
      this.getList()
    },
    handleAdd() {
      this.form = {
        propList: [
          {
            propLabel: undefined,
            propName: undefined,
          },
        ],
        thresholdList: [
          {
            label: undefined,
            value: undefined,
          },
        ],
        typeName: '',
        typeId: '',
        typeNum: '',
      }
      this.imageUrl = ''
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.disabled = false
    },
    handleDelete(row) {
      this.$confirm(this.$t('m.tip.DELECT_TIP'), this.$t('m.tip.TIPS'), {
        confirmButtonText: this.$t('m.CONFIRM'),
        cancelButtonText: this.$t('m.CANCEL'),
        type: 'warning',
      }).then(() => {
        delObj(row.typeId)
          .then(() => {
            this.getList()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000,
            })
          })
          .cache(() => {
            this.$notify({
              title: '失败',
              message: '删除失败',
              type: 'error',
              duration: 2000,
            })
          })
      })
    },
    handleEdit(row) {
      this.dialogStatus = 'update'
      this.form = {}
      this.disabled = false
      getObj(row.typeId).then((response) => {
        this.form = response.data
        if (
          this.form.thresholdList == null ||
          this.form.thresholdList == undefined
        ) {
          this.form.thresholdList = [
            {
              label: undefined,
              value: undefined,
            },
          ]
        }
        this.dialogFormVisible = true
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
      })
    },
    handleGet(row) {
      this.dialogStatus = 'get'
      this.form = {}
      this.disabled = true
      getObj(row.typeId).then((response) => {
        this.form = response.data
        this.dialogFormVisible = true
        this.dialogStatus = 'get'
        this.dialogFormVisible = true
      })
    },
    handleSearch() {
      this.listQuery.current = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.current = val
      this.getList()
    },
    create(formName) {
      const set = this.$refs
      set[formName].validate((valid) => {
        if (valid) {
          addObj(this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000,
            })
          })
        } else {
          return false
        }
      })
    },
    cancel(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
    },
    update(formName) {
      const set = this.$refs
      set[formName].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false
          putObj(this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000,
            })
          })
        } else {
          return false
        }
      })
    },
    async getDictList() {
      const res = await getTopDictListByDescNew('跳转类型')
      this.typeOptions = res.data
      const res1 = await getTopDictListByDescNew('是否')
      this.isShowOptions = res1.data
    },
    async getOrgList() {
      const res = await fetchOrgList()
      this.orgOptions = res.data
    },

    handleAvatarSuccess(res, file) {
      var url = res.true
      if (url == '' || url == undefined || url == 'undefined') {
        this.$notify({
          title: '失败',
          message: res.false,
          type: 'error',
          duration: 2000,
        })
        return
      }
      this.form.imgUrl = url // 表单提交
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    // 属性新增
    addDomain(e) {
      this.form.propList.push({
        propLabel: undefined,
        propName: undefined,
        key: Date.now(),
      })
      this.$forceUpdate()
    },
    // 阈值新增
    addThreshold(e) {
      this.form.thresholdList.push({
        label: undefined,
        value: undefined,
        key: Date.now(),
      })
      this.$forceUpdate()
    },
    change(e) {
      this.$forceUpdate()
    },
    removeDomain(item) {
      var index = this.form.propList.indexOf(item)
      if (index !== -1) {
        this.form.propList.splice(index, 1)
      }
      this.$forceUpdate()
    },
    removeThreshold(item) {
      var index = this.form.thresholdList.indexOf(item)
      if (index !== -1) {
        this.form.thresholdList.splice(index, 1)
      }
      this.$forceUpdate()
    },
  },
}
</script>


<style lang='scss' scoped>
.sort {
  .el-dialog .sort-dialog {
    overflow: hidden;
    max-height: 80% !important;
    margin: 0 auto !important;
    height: 90%;
    overflow: hidden;
    .el-dialog__body {
      .sort-scrollbar {
        width: 100%;
        height: 100%;
        overflow-y: auto;
      }
      .sort-scrollbar__wrap {
        width: auto;
        overflow-x: hidden;
      }
    }
  }
}
</style>

